package org.csu.linkgame.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import org.csu.linkgame.service.OSSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;

@Service("ossService")
public class QCloudOSSServiceImpl implements OSSService {

    @Autowired
    private COSClient cosClient;

    @Value("${QCloud.oss.region}")
    private String REGION;
    @Value("${QCloud.oss.bucket}")
    private String BUCKET_NAME;

    // 上传文件到通容器
    @Override
    public String upload(String localFilePath, String keyPath){
        try {
            // 指定要上传的文件
            File localFile = new File(localFilePath);
            // 指定要上传到的存储桶
            String bucketName = BUCKET_NAME;
            // 指定要上传到 COS 上对象键
            String key = keyPath;

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);

        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
            return "上传失败";
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
            return "上传失败";
        }
        String fileUrl = BUCKET_NAME+".cos."+REGION+".myqcloud.com/"+keyPath;
        return fileUrl;
    }
}
